from algorithm.Interpolator import Interpolator

class LinearInterpolator(Interpolator):
    def __init__(self, x_points, y_points):
        """
        初始化线性插值器
        :param x_points: 已知点的x坐标列表
        :param y_points: 已知点的y坐标列表
        """
        if len(x_points) != len(y_points):
            raise ValueError("x_points和y_points的长度必须相同")

        if x_points != sorted(x_points):
            sorted_indices = sorted(range(len(x_points)), key=lambda i: x_points[i])
            x_points = [x_points[i] for i in sorted_indices]
            y_points = [y_points[i] for i in sorted_indices]

        self.x_points = x_points
        self.y_points = y_points

    def interpolate(self, x):
        """
        在指定的x点进行插值
        :param x: 需要插值的x点
        :return: 插值结果y
        """
        for i in range(len(self.x_points) - 1):
            if self.x_points[i] <= x <= self.x_points[i + 1]:
                x0, y0 = self.x_points[i], self.y_points[i]
                x1, y1 = self.x_points[i + 1], self.y_points[i + 1]
                break
        else:
            raise ValueError(f"x={x} 不在已知点的范围内")

        slope = (y1 - y0) / (x1 - x0)
        y = y0 + slope * (x - x0)
        return y



if __name__ == "__main__":
    # 已知点的 x 坐标
    x_points = [1, 2, 3, 4, 5, 6, 7, 8]
    # 已知点的 y 坐标
    y_points = [2, 3, 5, 7, 11, 13, 17, 19]

    # 创建线性插值器
    interpolator = LinearInterpolator(x_points, y_points)

    x_values = [4.5, 6.5, 2.5]
    for x in x_values:
        y = interpolator.interpolate(x)
        print(f"在x={x}处的插值结果为: y={y}")